package com.android.example.app3;

import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.widget.Toast;

public class DownloadCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

            // 这里假设你知道哪个下载完成了，可能需要维护一个downloadId到文件路径的映射
            // 简化示例，假设只有一个下载任务
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            if (downloadManager != null) {
                Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(downloadId));
                if (cursor.moveToFirst()) {
                    // 检查 COLUMN_STATUS 列是否存在
                    int statusColumnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (statusColumnIndex != -1) {
                        if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(statusColumnIndex)) {
                            // 检查 COLUMN_LOCAL_URI 列是否存在
                            int uriColumnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
                            if (uriColumnIndex != -1) {
                                // 获取下载的文件路径
                                String uriString = cursor.getString(uriColumnIndex);
                                Uri apkUri = Uri.parse(uriString);

                                // 启动安装流程
                                installApk(context, apkUri);
                            }
                        }
                    }
                }
                cursor.close();
            }
        }
    }


    private void installApk(Context context, Uri apkUri) {
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 对于Android 7.0+，需要添加这个标志来正确处理文件URI
        installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        try {
            context.startActivity(installIntent);
        } catch (ActivityNotFoundException e) {
            // 没有安装能处理此 Intent 的应用
            Toast.makeText(context, "没有找到安装程序", Toast.LENGTH_SHORT).show();
        }
    }
}


